package com.wsoft.vo;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.wsoft.vo.session.LoginHrOrgVO;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 当前登录用户缓存对象
 *
 * @author: juiet
 * @date: 2024年09月03日 13:57
 */
@NoArgsConstructor
@Data
@JsonSerialize
@JsonIgnoreProperties(ignoreUnknown = true)
public class LoginUserDetail implements UserDetails,Serializable {
    private static final long serialVersionUID = -1;

    private LoginUserVO loginUserVO;
    private List<ResourceVO> resourceList;
    private Collection<GrantedAuthority> authorities;

    private Map<Class,Object> sessionVOs;

    public LoginUserDetail(LoginUserVO loginUserVO,List<ResourceVO> resourceList){
        this.loginUserVO = loginUserVO;
        this.resourceList = resourceList;
        this.authorities = resourceList.stream().map(resource -> new SimpleGrantedAuthority(resource.getId()+":"+resource.getName())).collect(Collectors.toList());
    }

    public Object getOneSessionVO(Class className){
        if(this.sessionVOs !=null){
            return sessionVOs.get(className);
        } else {
            return null;
        }
    }

    /**
     * 获取绩效组织id
     * @return
     */
    public Long getHrOrgId(){
        Object o = getOneSessionVO(LoginHrOrgVO.class);
        if (o == null){
            return null;
        }
        LoginHrOrgVO loginHrOrgVO = JSONObject.parseObject(JSONObject.toJSONString(o), LoginHrOrgVO.class);
        return loginHrOrgVO.getHrOrgId();
    }

    public void setOneSessionVO(Object object){
        if(this.sessionVOs !=null){
            this.sessionVOs.put(object.getClass(),object);
        } else {
            this.sessionVOs = new HashMap<>(16);
            this.sessionVOs.put(object.getClass(),object);
        }
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.loginUserVO.getLoginPw();
    }

    @Override
    public String getUsername() {
        return this.loginUserVO.getLoginName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return false;
    }

    @Override
    public boolean isAccountNonLocked() {
        return false;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return false;
    }

    @Override
    public boolean isEnabled() {
        return false;
    }
}
